/**
 *
 */
import Util;
import OSS;
import OpenPlatform;
import OSSUtil;
import FileForm;
import OpenApi;
import OpenApiUtil;
import EndpointUtil;

extends OpenApi;


init(config: OpenApi.Config){
  super(config);
  @endpointRule = 'regional';
  
  checkConfig(config);
  @endpoint = getEndpoint('imgsearch', @regionId, @endpointRule, @network, @suffix, @endpointMap, @endpoint);
}

function getEndpoint(productId: string, regionId: string, endpointRule: string, network: string, suffix: string, endpointMap: map[string]string, endpoint: string) throws: string{
  if (!Util.empty(endpoint)) {
    return endpoint;
  }
  
  if (!Util.isUnset(endpointMap) && !Util.empty(endpointMap[regionId])) {
    return endpointMap[regionId];
  }
  return EndpointUtil.getEndpointRules(productId, regionId, endpointRule, network, suffix);
}

model AddImageRequest {
  dbName?: string(name='DbName', example='default'),
  entityId?: string(name='EntityId', example='001'),
  extraData?: string(name='ExtraData'),
  imageUrl?: string(name='ImageUrl', example='https://viapi-test.oss-cn-shanghai.aliyuncs.com/test/imgsearch/xxxx.png'),
}

model AddImageAdvanceRequest {
  dbName?: string(name='DbName', example='default'),
  entityId?: string(name='EntityId', example='001'),
  extraData?: string(name='ExtraData'),
  imageUrlObject?: readable(name='ImageUrl', example='https://viapi-test.oss-cn-shanghai.aliyuncs.com/test/imgsearch/xxxx.png'),
}

model AddImageResponseBody = {
  data?: {
    dataId?: string(name='DataId', example='1585903814940000'),
  }(name='Data'),
  requestId?: string(name='RequestId', example='4DC6BB62-06D1-4242-939A-4AC500662E33'),
}

model AddImageResponse = {
  headers: map[string]string(name='headers'),
  statusCode: int32(name='statusCode'),
  body: AddImageResponseBody(name='body'),
}

async function addImageWithOptions(request: AddImageRequest, runtime: Util.RuntimeOptions): AddImageResponse {
  Util.validateModel(request);
  var body : map[string]any = {};
  if (!Util.isUnset(request.dbName)) {
    body['DbName'] = request.dbName;
  }
  if (!Util.isUnset(request.entityId)) {
    body['EntityId'] = request.entityId;
  }
  if (!Util.isUnset(request.extraData)) {
    body['ExtraData'] = request.extraData;
  }
  if (!Util.isUnset(request.imageUrl)) {
    body['ImageUrl'] = request.imageUrl;
  }
  var req = new OpenApi.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApi.Params{
    action = 'AddImage',
    version = '2020-03-20',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

async function addImage(request: AddImageRequest): AddImageResponse {
  var runtime = new Util.RuntimeOptions{};
  return addImageWithOptions(request, runtime);
}

async function addImageAdvance(request: AddImageAdvanceRequest, runtime: Util.RuntimeOptions): AddImageResponse {
  // Step 0: init client
  var accessKeyId = @credential.getAccessKeyId();
  var accessKeySecret = @credential.getAccessKeySecret();
  var securityToken = @credential.getSecurityToken();
  var credentialType = @credential.getType();
  var openPlatformEndpoint = @openPlatformEndpoint;
  if(Util.isUnset(openPlatformEndpoint)) {
    openPlatformEndpoint ='openplatform.aliyuncs.com';
  }
  if(Util.isUnset(credentialType)) {
    credentialType ='access_key';
  }
  var authConfig = new OpenApi.Config{
    accessKeyId = accessKeyId,
    accessKeySecret = accessKeySecret,
    securityToken = securityToken,
    type = credentialType,
    endpoint = openPlatformEndpoint,
    protocol = @protocol,
    regionId = @regionId,
  };
  var authClient = new OpenPlatform(authConfig);
  var authRequest = new OpenPlatform.AuthorizeFileUploadRequest{
    product = 'imgsearch',
    regionId = @regionId,
  };
  var authResponse = new OpenPlatform.AuthorizeFileUploadResponse{};
  var ossConfig = new OSS.Config{
    accessKeySecret = accessKeySecret,
    type = 'access_key',
    protocol = @protocol,
    regionId = @regionId,
  };
  var ossClient : OSS = null;

  var fileObj = new FileForm.FileField{};
  var ossHeader = new OSS.PostObjectRequest.header{};
  var uploadRequest = new OSS.PostObjectRequest{};
  var ossRuntime = new OSSUtil.RuntimeOptions{};
  OpenApiUtil.convert(runtime, ossRuntime);
  var addImageReq = new AddImageRequest{};
  OpenApiUtil.convert(request, addImageReq);

  if(!Util.isUnset(request.imageUrlObject)) {
    authResponse = authClient.authorizeFileUploadWithOptions(authRequest, runtime);
    ossConfig.accessKeyId = authResponse.body.accessKeyId;
    ossConfig.endpoint = OpenApiUtil.getEndpoint(authResponse.body.endpoint, authResponse.body.useAccelerate, @endpointType);
    ossClient = new OSS(ossConfig);

    fileObj = new FileForm.FileField{
      filename = authResponse.body.objectKey,
      content = request.imageUrlObject,
      contentType = '',
    };
    ossHeader = new OSS.PostObjectRequest.header{
      accessKeyId = authResponse.body.accessKeyId,
      policy = authResponse.body.encodedPolicy,
      signature = authResponse.body.signature,
      key = authResponse.body.objectKey,
      file = fileObj,
      successActionStatus = '201',
    };
    uploadRequest = new OSS.PostObjectRequest{
      bucketName = authResponse.body.bucket,
      header = ossHeader,
    };
    ossClient.postObject(uploadRequest, ossRuntime);
    addImageReq.imageUrl = `http://${authResponse.body.bucket}.${authResponse.body.endpoint}/${authResponse.body.objectKey}`;
  }
  var addImageResp = addImageWithOptions(addImageReq, runtime);
  return addImageResp;
}

model CreateImageDbRequest {
  name?: string(name='Name', example='default'),
}

model CreateImageDbResponseBody = {
  requestId?: string(name='RequestId', example='DD106AE3-838A-41D7-8CD0-B902DC2BC109'),
}

model CreateImageDbResponse = {
  headers: map[string]string(name='headers'),
  statusCode: int32(name='statusCode'),
  body: CreateImageDbResponseBody(name='body'),
}

async function createImageDbWithOptions(request: CreateImageDbRequest, runtime: Util.RuntimeOptions): CreateImageDbResponse {
  Util.validateModel(request);
  var body : map[string]any = {};
  if (!Util.isUnset(request.name)) {
    body['Name'] = request.name;
  }
  var req = new OpenApi.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApi.Params{
    action = 'CreateImageDb',
    version = '2020-03-20',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

async function createImageDb(request: CreateImageDbRequest): CreateImageDbResponse {
  var runtime = new Util.RuntimeOptions{};
  return createImageDbWithOptions(request, runtime);
}

model DeleteImageRequest {
  dbName?: string(name='DbName', example='default'),
  entityId?: string(name='EntityId', example='1'),
}

model DeleteImageResponseBody = {
  requestId?: string(name='RequestId', example='3F3F81A5-4C37-4716-AE5C-518D2537365C'),
}

model DeleteImageResponse = {
  headers: map[string]string(name='headers'),
  statusCode: int32(name='statusCode'),
  body: DeleteImageResponseBody(name='body'),
}

async function deleteImageWithOptions(request: DeleteImageRequest, runtime: Util.RuntimeOptions): DeleteImageResponse {
  Util.validateModel(request);
  var body : map[string]any = {};
  if (!Util.isUnset(request.dbName)) {
    body['DbName'] = request.dbName;
  }
  if (!Util.isUnset(request.entityId)) {
    body['EntityId'] = request.entityId;
  }
  var req = new OpenApi.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApi.Params{
    action = 'DeleteImage',
    version = '2020-03-20',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

async function deleteImage(request: DeleteImageRequest): DeleteImageResponse {
  var runtime = new Util.RuntimeOptions{};
  return deleteImageWithOptions(request, runtime);
}

model DeleteImageDbRequest {
  name?: string(name='Name', example='default'),
}

model DeleteImageDbResponseBody = {
  requestId?: string(name='RequestId', example='3F3F81A5-4C37-4716-AE5C-518D2537365C'),
}

model DeleteImageDbResponse = {
  headers: map[string]string(name='headers'),
  statusCode: int32(name='statusCode'),
  body: DeleteImageDbResponseBody(name='body'),
}

async function deleteImageDbWithOptions(request: DeleteImageDbRequest, runtime: Util.RuntimeOptions): DeleteImageDbResponse {
  Util.validateModel(request);
  var body : map[string]any = {};
  if (!Util.isUnset(request.name)) {
    body['Name'] = request.name;
  }
  var req = new OpenApi.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApi.Params{
    action = 'DeleteImageDb',
    version = '2020-03-20',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

async function deleteImageDb(request: DeleteImageDbRequest): DeleteImageDbResponse {
  var runtime = new Util.RuntimeOptions{};
  return deleteImageDbWithOptions(request, runtime);
}

model ListImageDbsResponseBody = {
  data?: {
    dbList?: [ 
      {
        name?: string(name='Name', example='default'),
      }
    ](name='DbList'),
  }(name='Data'),
  requestId?: string(name='RequestId', example='4E010B89-B370-458A-A586-B9A9F3BC3058'),
}

model ListImageDbsResponse = {
  headers: map[string]string(name='headers'),
  statusCode: int32(name='statusCode'),
  body: ListImageDbsResponseBody(name='body'),
}

async function listImageDbsWithOptions(runtime: Util.RuntimeOptions): ListImageDbsResponse {
  var req = new OpenApi.OpenApiRequest{};
  var params = new OpenApi.Params{
    action = 'ListImageDbs',
    version = '2020-03-20',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

async function listImageDbs(): ListImageDbsResponse {
  var runtime = new Util.RuntimeOptions{};
  return listImageDbsWithOptions(runtime);
}

model ListImagesRequest {
  dbName?: string(name='DbName', example='default'),
  entityIdPrefix?: string(name='EntityIdPrefix', example='U1'),
  limit?: int32(name='Limit', example='50'),
  offset?: int32(name='Offset', example='1'),
  order?: string(name='Order', example='asc'),
  token?: string(name='Token', example='2'),
}

model ListImagesResponseBody = {
  data?: {
    imageList?: [ 
      {
        createdAt?: long(name='CreatedAt', example='1582838489213'),
        dataId?: string(name='DataId', example='001'),
        entityId?: string(name='EntityId', example='5'),
        extraData?: string(name='ExtraData'),
        updatedAt?: long(name='UpdatedAt', example='1582838489213'),
      }
    ](name='ImageList'),
    token?: string(name='Token', example='2'),
    totalCount?: int32(name='TotalCount', example='100'),
  }(name='Data'),
  requestId?: string(name='RequestId', example='2B93C43A-F824-40C8-AF79-844342B0F43A'),
}

model ListImagesResponse = {
  headers: map[string]string(name='headers'),
  statusCode: int32(name='statusCode'),
  body: ListImagesResponseBody(name='body'),
}

async function listImagesWithOptions(request: ListImagesRequest, runtime: Util.RuntimeOptions): ListImagesResponse {
  Util.validateModel(request);
  var body : map[string]any = {};
  if (!Util.isUnset(request.dbName)) {
    body['DbName'] = request.dbName;
  }
  if (!Util.isUnset(request.entityIdPrefix)) {
    body['EntityIdPrefix'] = request.entityIdPrefix;
  }
  if (!Util.isUnset(request.limit)) {
    body['Limit'] = request.limit;
  }
  if (!Util.isUnset(request.offset)) {
    body['Offset'] = request.offset;
  }
  if (!Util.isUnset(request.order)) {
    body['Order'] = request.order;
  }
  if (!Util.isUnset(request.token)) {
    body['Token'] = request.token;
  }
  var req = new OpenApi.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApi.Params{
    action = 'ListImages',
    version = '2020-03-20',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

async function listImages(request: ListImagesRequest): ListImagesResponse {
  var runtime = new Util.RuntimeOptions{};
  return listImagesWithOptions(request, runtime);
}

model SearchImageRequest {
  dbName?: string(name='DbName', example='default'),
  imageUrl?: string(name='ImageUrl', example='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imgsearch/SearchImage/SearchImage-ku8.png'),
  limit?: int32(name='Limit', example='5'),
}

model SearchImageAdvanceRequest {
  dbName?: string(name='DbName', example='default'),
  imageUrlObject?: readable(name='ImageUrl', example='http://viapi-test.oss-cn-shanghai.aliyuncs.com/viapi-3.0domepic/imgsearch/SearchImage/SearchImage-ku8.png'),
  limit?: int32(name='Limit', example='5'),
}

model SearchImageResponseBody = {
  data?: {
    matchList?: [ 
      {
        dataId?: string(name='DataId', example='001'),
        entityId?: string(name='EntityId', example='123456'),
        extraData?: string(name='ExtraData', example='tangyan'),
        imageUrl?: string(name='ImageUrl', example='http://vision-console.oss-cn-shanghai.aliyuncs.com/1902352443710590/kv6dvd1ie0c6-ipvnszc8584116.jpg?Expires=1635150265&OSSAccessKeyId=LTAI4Fp1Gt5RzwdEXL3o****&Signature=8rj0%2Bxg%2Bni5NxQAcEQqISX5j1w****'),
        score?: float(name='Score', example='10'),
      }
    ](name='MatchList'),
  }(name='Data'),
  requestId?: string(name='RequestId', example='A98DBCEB-45E2-5F5F-B5ED-F2340182FD87'),
}

model SearchImageResponse = {
  headers: map[string]string(name='headers'),
  statusCode: int32(name='statusCode'),
  body: SearchImageResponseBody(name='body'),
}

async function searchImageWithOptions(request: SearchImageRequest, runtime: Util.RuntimeOptions): SearchImageResponse {
  Util.validateModel(request);
  var body : map[string]any = {};
  if (!Util.isUnset(request.dbName)) {
    body['DbName'] = request.dbName;
  }
  if (!Util.isUnset(request.imageUrl)) {
    body['ImageUrl'] = request.imageUrl;
  }
  if (!Util.isUnset(request.limit)) {
    body['Limit'] = request.limit;
  }
  var req = new OpenApi.OpenApiRequest{ 
    body = OpenApiUtil.parseToMap(body),
  };
  var params = new OpenApi.Params{
    action = 'SearchImage',
    version = '2020-03-20',
    protocol = 'HTTPS',
    pathname = '/',
    method = 'POST',
    authType = 'AK',
    style = 'RPC',
    reqBodyType = 'formData',
    bodyType = 'json',
  };
  return callApi(params, req, runtime);
}

async function searchImage(request: SearchImageRequest): SearchImageResponse {
  var runtime = new Util.RuntimeOptions{};
  return searchImageWithOptions(request, runtime);
}

async function searchImageAdvance(request: SearchImageAdvanceRequest, runtime: Util.RuntimeOptions): SearchImageResponse {
  // Step 0: init client
  var accessKeyId = @credential.getAccessKeyId();
  var accessKeySecret = @credential.getAccessKeySecret();
  var securityToken = @credential.getSecurityToken();
  var credentialType = @credential.getType();
  var openPlatformEndpoint = @openPlatformEndpoint;
  if(Util.isUnset(openPlatformEndpoint)) {
    openPlatformEndpoint ='openplatform.aliyuncs.com';
  }
  if(Util.isUnset(credentialType)) {
    credentialType ='access_key';
  }
  var authConfig = new OpenApi.Config{
    accessKeyId = accessKeyId,
    accessKeySecret = accessKeySecret,
    securityToken = securityToken,
    type = credentialType,
    endpoint = openPlatformEndpoint,
    protocol = @protocol,
    regionId = @regionId,
  };
  var authClient = new OpenPlatform(authConfig);
  var authRequest = new OpenPlatform.AuthorizeFileUploadRequest{
    product = 'imgsearch',
    regionId = @regionId,
  };
  var authResponse = new OpenPlatform.AuthorizeFileUploadResponse{};
  var ossConfig = new OSS.Config{
    accessKeySecret = accessKeySecret,
    type = 'access_key',
    protocol = @protocol,
    regionId = @regionId,
  };
  var ossClient : OSS = null;

  var fileObj = new FileForm.FileField{};
  var ossHeader = new OSS.PostObjectRequest.header{};
  var uploadRequest = new OSS.PostObjectRequest{};
  var ossRuntime = new OSSUtil.RuntimeOptions{};
  OpenApiUtil.convert(runtime, ossRuntime);
  var searchImageReq = new SearchImageRequest{};
  OpenApiUtil.convert(request, searchImageReq);

  if(!Util.isUnset(request.imageUrlObject)) {
    authResponse = authClient.authorizeFileUploadWithOptions(authRequest, runtime);
    ossConfig.accessKeyId = authResponse.body.accessKeyId;
    ossConfig.endpoint = OpenApiUtil.getEndpoint(authResponse.body.endpoint, authResponse.body.useAccelerate, @endpointType);
    ossClient = new OSS(ossConfig);

    fileObj = new FileForm.FileField{
      filename = authResponse.body.objectKey,
      content = request.imageUrlObject,
      contentType = '',
    };
    ossHeader = new OSS.PostObjectRequest.header{
      accessKeyId = authResponse.body.accessKeyId,
      policy = authResponse.body.encodedPolicy,
      signature = authResponse.body.signature,
      key = authResponse.body.objectKey,
      file = fileObj,
      successActionStatus = '201',
    };
    uploadRequest = new OSS.PostObjectRequest{
      bucketName = authResponse.body.bucket,
      header = ossHeader,
    };
    ossClient.postObject(uploadRequest, ossRuntime);
    searchImageReq.imageUrl = `http://${authResponse.body.bucket}.${authResponse.body.endpoint}/${authResponse.body.objectKey}`;
  }
  var searchImageResp = searchImageWithOptions(searchImageReq, runtime);
  return searchImageResp;
}

